package com.yunjinsuke.recharge.service;

import com.yunjinsuke.recharge.common.ObjectId;
import com.yunjinsuke.recharge.entity.Merchant;
import com.yunjinsuke.recharge.redis.RedisKeyUtil;
import com.yunjinsuke.recharge.redis.RedisUtil;
import com.yunjinsuke.recharge.repository.MerchantRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class MerchantService {

    private final RedisUtil redisUtil;

    private final MerchantRepository merchantRepository;

    public MerchantService(MerchantRepository merchantRepository, RedisUtil redisUtil) {
        this.merchantRepository = merchantRepository;
        this.redisUtil = redisUtil;
    }

    /**
     * 创建商户
     *
     * @return 商户信息
     */
    public Merchant createMerchant() {
        Merchant merchant = new Merchant();
        merchant.setAppId(ObjectId.getId());
        merchant.setMchKey(UUID.randomUUID().toString());
        merchant.setId(ObjectId.getId());
        merchant = merchantRepository.save(merchant);
        // 存储
        redisUtil.set(RedisKeyUtil.appKey(merchant.getAppId()), merchant);
        redisUtil.set(RedisKeyUtil.merchantKey(merchant.getId(), merchant.getMchKey()), null);
        return merchant;
    }

    /**
     * 获取所有商户列表
     *
     * @return 所有商户列表
     */
    public List<Merchant> getAllMerchantList() {
        return merchantRepository.findAll();
    }

}
